﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using RCREEE.Library.Entities;
using RCREEE.Web.Classes;
using RCREEE.Library;
using System.Drawing;

namespace RCREEE.Web
{
    public partial class GeorgeCountry : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //MultiView1.ActiveViewIndex = 0;
                //// Add language Code to the current session
                //Session.Add("LanguageCode", 1033);

                #region Table Permissions
                //// Table declarations
                //DataTable dtPermissions = new DataTable();

                //dtPermissions.Columns.Add("CountryId", typeof(int));
                //dtPermissions.Columns.Add("CanAdd", typeof(bool));
                //dtPermissions.Columns.Add("CanEdit", typeof(bool));
                ////dtPermissions.Columns.Add("CanDelete", typeof(bool));

                //// New Row .. assigning permissions
                //DataRow drPermission = dtPermissions.NewRow();
                //drPermission["CountryId"] = 1;
                //drPermission["CanAdd"] = true;
                //drPermission["CanEdit"] = true;
                ////drPermission["CanDelete"] = false;

                //dtPermissions.Rows.Add(drPermission);

                //// Add table to the session object
                //Session.Add("dtPermissions", dtPermissions);

                #endregion

                int countryId = 0;

                if (Request["C"] != null && Request["C"].ToString() != "")
                    countryId = Convert.ToInt32(Request["C"]);

                else if (Session["CountryId"] != null)
                    countryId = Convert.ToInt32(Session["CountryId"]);

                if (countryId != 0)
                {
                    ddlCountries.SelectedValue = Convert.ToString(countryId);
                }

            }
        }


        protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCountries.SelectedValue != null && ddlCountries.SelectedValue != "0")
                fvCountryDetails.DataBind();
            else
            {
                fvCountryDetails.DataSource = null;
                fvCountryDetails.DataBind();
            }
        }

        protected void fvCountryDetails_DataBound(object sender, EventArgs e)
        {
            if (fvCountryDetails.CurrentMode == FormViewMode.ReadOnly)
            {
                int LanguageCode = Convert.ToInt32(Session["languageCode"]);

                switch (LanguageCode)
                {
                    case 1033:
                        {
                            try
                            {
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsEnglish")).Visible = true;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsFrench")).Visible = false;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsArabic")).Visible = false;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }
                    case 1036:
                        {
                            try
                            {
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsEnglish")).Visible = false;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsFrench")).Visible = true;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsArabic")).Visible = false;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }
                    case 1025:
                        {
                            try
                            {
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsEnglish")).Visible = false;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsFrench")).Visible = false;
                                ((Panel)fvCountryDetails.FindControl("pnlDetailsArabic")).Visible = true;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }

                }
                try
                {
                    ((Button)(fvCountryDetails.FindControl("EditButton"))).Visible = Can("Update", Convert.ToInt32(ddlCountries.SelectedValue));
                    ((Button)(fvCountryDetails.FindControl("DeleteButton"))).Visible = Can("Delete", Convert.ToInt32(ddlCountries.SelectedValue));
                    ((Button)(fvCountryDetails.FindControl("NewButton"))).Visible = Can("Add", Convert.ToInt32(ddlCountries.SelectedValue));
                }
                catch (Exception exp)
                {

                }
                if (((GridView)fvCountryDetails.FindControl("gvEnergyItems")) != null)
                    PopulateGrid();

                if (((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_RE")) != null)
                    PopulateStrategicObjectivesGrids();

            }
        }

        protected void fvCountryDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            e.NewValues["FlagImagePath"] = "c";

            if (e.NewValues["EnglishRenewableEnergyContributionRate"] == "")
                e.NewValues["EnglishRenewableEnergyContributionRate"] = null;

            if (e.NewValues["EnglishEnergyEfficiencyContributionRate"] == "")
                e.NewValues["EnglishEnergyEfficiencyContributionRate"] = null;

            if (e.NewValues["FrenchRenewableEnergyContributionRate"] == "")
                e.NewValues["FrenchRenewableEnergyContributionRate"] = null;

            if (e.NewValues["FrenchEnergyEfficiencyContributionRate"] == "")
                e.NewValues["FrenchEnergyEfficiencyContributionRate"] = null;

            if (e.NewValues["ArabicRenewableEnergyContributionRate"] == "")
                e.NewValues["ArabicRenewableEnergyContributionRate"] = null;

            if (e.NewValues["ArabicEnergyEfficiencyContributionRate"] == "")
                e.NewValues["ArabicEnergyEfficiencyContributionRate"] = null;

        }

        protected void fvCountryDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            e.Values["FlagImagePath"] = "c";

            if (e.Values["EnglishRenewableEnergyContributionRate"] == "")
                e.Values["EnglishRenewableEnergyContributionRate"] = null;

            if (e.Values["EnglishEnergyEfficiencyContributionRate"] == "")
                e.Values["EnglishEnergyEfficiencyContributionRate"] = null;

            if (e.Values["FrenchRenewableEnergyContributionRate"] == "")
                e.Values["FrenchRenewableEnergyContributionRate"] = null;

            if (e.Values["FrenchEnergyEfficiencyContributionRate"] == "")
                e.Values["FrenchEnergyEfficiencyContributionRate"] = null;

            if (e.Values["ArabicRenewableEnergyContributionRate"] == "")
                e.Values["ArabicRenewableEnergyContributionRate"] = null;

            if (e.Values["ArabicEnergyEfficiencyContributionRate"] == "")
                e.Values["ArabicEnergyEfficiencyContributionRate"] = null;
        }

        protected void btnDisplay_Click(object sender, EventArgs e)
        {
            //if (MultiView1.ActiveViewIndex == 0)
            //    MultiView1.ActiveViewIndex = 1;
            //else
            //    MultiView1.ActiveViewIndex = 0;
        }

        private void PopulateGrid()
        {
            if (ddlCountries.SelectedValue == null || ddlCountries.SelectedValue == "0")
            {

                ((GridView)fvCountryDetails.FindControl("gvEnergyItems")).DataSource = null;
                ((GridView)fvCountryDetails.FindControl("gvEnergyItems")).DataBind();
            }
            EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();
            DataTable dtEnergyItems = _energy.GetAllEnergyConsumptionDevelopmentItemValues(Convert.ToInt32(Session["LanguageCode"]), Convert.ToInt32(ddlCountries.SelectedValue));
            DataTable dtFinalTable = dtEnergyItems.Clone();


            DataRow[] drParents = dtEnergyItems.Select("ParentItemId = 0");

            foreach (DataRow dr in drParents)
            {
                int level = 1;
                dtFinalTable.Rows.Add(dr.ItemArray);
                AddChildren(dtEnergyItems, ref dtFinalTable, Convert.ToInt32(dr["ItemId"]), ref level);
            }

            dtFinalTable.Columns.Remove("ItemId");
            dtFinalTable.Columns.Remove("ParentItemId");
            //dtFinalTable.Columns.Remove("IsMajor");

            ((GridView)fvCountryDetails.FindControl("gvEnergyItems")).DataSource = dtFinalTable;
            ((GridView)fvCountryDetails.FindControl("gvEnergyItems")).DataBind();

        }

        private void PopulateStrategicObjectivesGrids()
        {
            if (ddlCountries.SelectedValue != "0" && ddlCountries.SelectedValue != null)
            {
                int _countryId = Convert.ToInt32(ddlCountries.SelectedValue);

                int _languageCode = 1033;
                if (Session["LanguageCode"] != null)
                    _languageCode = Convert.ToInt32(Session["LanguageCode"]);

                StrategicObjectives _strategicObjective = new StrategicObjectives();
                DataSet dsItems = _strategicObjective.GetAllStrategicObjectivesItemValues(_languageCode, _countryId);

                if (dsItems != null && dsItems.Tables[0].Rows.Count > 0)
                {
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_EE")).DataSource = dsItems.Tables[0];
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_EE")).DataBind();
                }
                else
                {
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_EE")).DataSource = null;
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_EE")).DataBind();
                }

                if (dsItems != null && dsItems.Tables[1].Rows.Count > 0)
                {
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_RE")).DataSource = dsItems.Tables[1];
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_RE")).DataBind();
                }
                else
                {
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_RE")).DataSource = null;
                    ((GridView)fvCountryDetails.FindControl("gvStrategicObjectives_RE")).DataBind();
                }
            }
        }

        private void AddChildren(DataTable dtSource, ref DataTable dtDestination, int ItemId, ref int level)
        {
            int currentLevel = level;
            level++;
            DataRow[] drChildren = dtSource.Select("ParentItemId=" + ItemId.ToString());
            if (drChildren.Length > 0)
            {
                foreach (DataRow drChild in drChildren)
                {
                    drChild["ItemName"] = GetSpacing(currentLevel) + drChild["ItemName"].ToString();
                    drChild.AcceptChanges();
                    dtDestination.Rows.Add(drChild.ItemArray);

                    AddChildren(dtSource, ref dtDestination, Convert.ToInt32(drChild["ItemId"]), ref level);
                }
            }
        }

        private string GetSpacing(int level)
        {
            string spacing = "";
            for (int i = 0; i < level; i++)
                spacing += " -- ";

            return spacing;
        }

        protected void gvEnergyItems_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell _cell in e.Row.Cells)
                    _cell.Width = Unit.Pixel(100);
            }
            else
            {
                e.Row.Cells[0].Width = Unit.Pixel(400);
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;

            }
            // hide is major column
            e.Row.Cells[1].Visible = false;
        }

        protected void gvEnergyItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
                if (((CheckBox)e.Row.Cells[1].Controls[0]).Checked)
                {
                    int colSpan = ((DataTable)((GridView)fvCountryDetails.FindControl("gvEnergyItems")).DataSource).Columns.Count;
                    for (int i = 1; i < colSpan; i++)
                    {
                        e.Row.Cells[i].Visible = false;
                        e.Row.Cells[i].Controls.Clear();
                    }

                    e.Row.Cells[0].Attributes["ColSpan"] = (colSpan).ToString();
                    e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    e.Row.Cells[0].BackColor = Color.FromArgb(2, 104, 176);
                    e.Row.Cells[0].ForeColor = System.Drawing.Color.White;
                }

        }

        //protected void btnUploadImage_Click(object sender, EventArgs e)
        //{
        //    if (((FileUpload)fvCountryDetails.FindControl("flagImageUpload")).HasFile)
        //    {
        //        try
        //        {
        //            ((FileUpload)fvCountryDetails.FindControl("flagImageUpload")).SaveAs(Server.MapPath("~/Images/Flags/" + 
        //                ((TextBox)fvCountryDetails.FindControl("txtEnglishName_Edit")).Text +".jpeg"));
        //        }
        //        catch (Exception exp)
        //        {

        //        }
        //    }

        //}

        public bool Can(string permission, int CountryId)
        {
            //if (Session["dtPermissions"] == null)
            //{
            //    #region Table Permissions
            //    // Table declarations
            //    DataTable dtPermissions = new DataTable();

            //    dtPermissions.Columns.Add("CountryId", typeof(int));
            //    dtPermissions.Columns.Add("CanAdd", typeof(bool));
            //    dtPermissions.Columns.Add("CanEdit", typeof(bool));
            //    //dtPermissions.Columns.Add("CanDelete", typeof(bool));

            //    // New Row .. assigning permissions
            //    DataRow drPermission = dtPermissions.NewRow();
            //    drPermission["CountryId"] = 1;
            //    drPermission["CanAdd"] = true;
            //    drPermission["CanEdit"] = true;
            //    //drPermission["CanDelete"] = false;

            //    dtPermissions.Rows.Add(drPermission);

            //    Session.Remove("dtPermissions");

            //    // Add table to the session object
            //    Session.Add("dtPermissions", dtPermissions);
            //    #endregion
            //}
            try
            {
                DataRow[] dr = ((DataTable)Session["Permissions"]).Select("CountryId = " + CountryId.ToString());

                if (dr.Length > 0)
                {
                    return Convert.ToBoolean(dr[0]["Can" + permission]);
                }
                else
                    return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        protected void fvCountryDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            ddlCountries.DataBind();
        }

        private void ExportToExcel(DataTable dataTable, List<string> validColumns)
        {
            try
            {

                GridView gridView = Helper.ExportToExcel(dataTable, validColumns);


                Response.Clear();

                Response.AddHeader("content-disposition", "attachment; filename=\"Product Numbers Generated on (" + DateTime.Now.Date.ToString("d MMM yyyy") + ").xls\"");

                Response.Charset = "";

                // If you want the option to open the Excel file without saving than

                // comment out the line below

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/vnd.xls";

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();

                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                gridView.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());

                Response.End();
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }

        protected void btnExportContacts_Click(object sender, EventArgs e)
        {
            //// Get the current Item Index
            //Button currentButton = sender as Button;
            //int repeaterItemIndex = ((RepeaterItem)currentButton.NamingContainer).ItemIndex;
            int repeaterItemIndex;
            int.TryParse(hdnExportIndex.Value, out repeaterItemIndex);

            // Get the current Entity Id
            int EntityId = Convert.ToInt32(((Label)((Repeater)fvCountryDetails.FindControl("RepeaterContact")).Controls[repeaterItemIndex].FindControl("lblContactEntityId")).Text);

            // Get Data according to the current data: EntityId, LanguageCode, CountryId
            Library.Entities.Contact _Contact = new Library.Entities.Contact();
            DataTable dtAllContact = _Contact.GetAllMasterContacts(EntityId, Convert.ToInt32(Session["LanguageCode"]), Convert.ToInt32(ddlCountries.SelectedValue));
            List<string> validColumns = new List<string> { "ContactName", "FieldName", "FieldName", "FaxNumber", "Email" };
            ExportToExcel(dtAllContact, validColumns);
        }

        protected void RepeaterContact_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item)
            {
                //UpdatePanelControlTrigger  trigger = new PostBackTrigger();
                Button _button = (Button)((Repeater)fvCountryDetails.FindControl("RepeaterContact")).Controls[e.Item.ItemIndex].FindControl("btnExportContacts");
                _button.OnClientClick = string.Format("HandelExport('{0}')", e.Item.ItemIndex);
                // trigger.ControlID = _button.UniqueID;
                //updatePanel1.Triggers.Add(trigger);
                //GridView _grid = (GridView)((Repeater)fvCountryDetails.FindControl("RepeaterContact")).Controls[e.Item.ItemIndex].FindControl("gvMaster");
                //if (_grid.DataSource == null)
                //    _button.Visible = false;
                //else
                //    _button.Visible = true;
            }
        }

        protected void btnExportProjects_Click(object sender, EventArgs e)
        {
            int repeaterItemIndex;
            int.TryParse(hdnExportIndex.Value, out repeaterItemIndex);

            // Get the current Entity Id
            int EntityId = Convert.ToInt32(((Label)((Repeater)fvCountryDetails.FindControl("RepeaterProjects")).Controls[repeaterItemIndex].FindControl("lblProjectEntityId")).Text);

            // Get Data according to the current data: EntityId, LanguageCode, CountryId
            List<string> validColumns = new List<string> { "Name", "ProjectType", "Place", "OperationYear", "ExecutingAgency" };
            var dtProjects = DataManager.SelectProjectsByCountry(Convert.ToInt32(Session["LanguageCode"]),
                                                                Convert.ToInt32(ddlCountries.SelectedValue),
                                                                EntityId);
            ExportToExcel(dtProjects, validColumns);
        }

        protected void RepeaterProjects_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Button _button = (Button)((Repeater)fvCountryDetails.FindControl("RepeaterProjects")).Controls[e.Item.ItemIndex].FindControl("btnExportProjects");
            _button.OnClientClick = string.Format("HandelExportProjects('{0}')", e.Item.ItemIndex);
        }

        protected void fvCountryDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            //e.Values["LanguageCode"] = Convert.ToInt32(Session["LanguageCode"]);
        }

        protected void fvCountryDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            Page.Response.Redirect("CountrySelector.aspx");
        }
    }
}